<template>
  <div>
    <el-form ref="myform" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="formItem.username" placeholder="请输入用户名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="formItem.name" placeholder="请输入姓名" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="!edited">
        <el-col :span="12">
          <el-form-item label="密码" prop="password">
            <el-input v-model="formItem.password" type="password" style="position:fixed;bottom:-9999px;display:none;" />
            <el-input v-model="formItem.password" type="password" autocomplete="new-password" placeholder="请输入密码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="确认密码" prop="passwordAgain">
            <el-input v-model="formItem.passwordAgain" type="password" placeholder="请再次输入密码" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="部门" prop="oganizations">
            <treeselect
              v-model="formItem.oganizations"
              :multiple="true"
              :options="availableOganizations"
              :load-options="loadOptions"
              placeholder="请选择使用部门"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="角色" prop="roles">
            <el-select v-model="formItem.roles" multiple placeholder="请选择角色">
              <el-option
                v-for="item in availableRoles"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="电话" prop="phone">
            <el-input v-model="formItem.phone" placeholder="请输入电话" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="mail">
            <el-input v-model="formItem.mail" placeholder="请输入邮箱" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="启用" prop="enabled">
            <el-switch v-model="formItem.enabled" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { create, update, detail } from '@neu/auth-ui/api/user'
import { list } from '@neu/auth-ui/api/role'
import { tree } from '@neu/auth-ui/api/organization'

// 定义一个表单原始项
const formItem = {
  username: '',
  password: '',
  passwordAgain: '',
  name: '',
  phone: '',
  mail: '',
  locked: false,
  enabled: true,
  roles: [],
  oganizations: []
}

export default {
  name: 'UsersEditForm',
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.formItem.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      formItem: { ...formItem },
      // 表单验证规则
      rules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '电话不能为空', trigger: 'blur' }
        ],
        mail: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
        ],
        roles: [
          { required: true, type: 'array', min: 1, message: '请至少选择一个角色', trigger: 'change' }
        ],
        oganizations: [
          { required: true, type: 'array', min: 1, message: '请至少选择一个部门', trigger: 'change' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 18, message: '6~18位密码', trigger: 'blur' }
        ],
        passwordAgain: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ]
      },
      availableRoles: [],
      availableOganizations: null
    }
  },
  computed: {
    edited() {
      return this.id !== -1
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: function() {
      this.fetch()
    }
  },
  created() {
    list().then(response => {
      this.availableRoles = response.data
    })
    // 表单组件放在diaolog中，首次打开时，监控不到id的变化。所以需要在created中调用一次
    this.fetch()
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          this.formItem = {
            ...response.data,
            password: '',
            roles: response.data.roles.map(it => it.code),
            oganizations: response.data.oganizations.map(it => it.code)
          }
        })
      } else {
        this.formItem = { ...formItem }
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      const updated = this.edited
      return new Promise(resolve => {
        this.$refs.myform.validate((valid) => {
          if (valid) {
            if (updated) {
              resolve(update(this.id, this.formItem))
            } else {
              resolve(create(this.formItem))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.myform.resetFields()
    },
    loadOptions({ action }) {
      if (action === 'LOAD_ROOT_OPTIONS') {
        return tree().then(response => {
          this.availableOganizations = [response.data]
        })
      }
    }
  }
}
</script>
